package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author : [wangtao]
 * @className : AddressBookController
 * @description : []
 * @createTime : [2022/10/13 13:03]
 * @updateTime : [2022/10/13 13:03]
 */
@RequestMapping("/addressBook")
@RestController
@Slf4j
public class AddressBookController {
@Autowired
private AddressBookService addressBookService;

    @PostMapping
    public R add(@RequestBody AddressBook addressBook, HttpSession session) {
        Long userId = (Long) session.getAttribute("userId");
        addressBook.setUserId(userId);
        addressBookService.save(addressBook);
        return R.success("添加成功");
    }

    @GetMapping("/default")
    public R<AddressBook> setDefault(AddressBook addressBook) {

        Long id = BaseContext.getCurrentId();
        LambdaUpdateWrapper<AddressBook> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(id != null, AddressBook::getUserId, id);
        AddressBook one = addressBookService.getOne(lqw);
        one.setIsDefault(1);
         addressBookService.updateById(one);
            return R.success(one);


    }
    @GetMapping("/{id}")
    public R<AddressBook> updateShow(@PathVariable Long id) {
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(id != null, AddressBook::getId, id);
        AddressBook address = addressBookService.getOne(lqw);
        return R.success(address);

    }

    @PutMapping
    public R updateSave(@RequestBody AddressBook addressBook) {
        addressBookService.updateById(addressBook);
        return R.success("更新成功");
    }

    @DeleteMapping
    public R delete(Long ids) {
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ids != null, AddressBook::getId, ids);
        addressBookService.remove(lqw);
        return R.success("删除成功");
    }

    @GetMapping("/list")
    public R<List<AddressBook>> list(AddressBook addressBook) {
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper();
        addressBook.setUserId(BaseContext.getCurrentId());
        lqw.eq(addressBook.getUserId() != null, AddressBook::getUserId,addressBook.getUserId()).orderByAsc(AddressBook::getUpdateTime);
        List<AddressBook> list = addressBookService.list(lqw);
        return R.success(list);

    }
}
